package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.auth.remote.AuthRemote;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserReq;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AuthServiceImpl
 * @Description 描述
 * @Author ShiYu.Cui
 * @Date 2024/4/25 9:01
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthRemote authRemote;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result login(UserReq userReq) {
        if(StringUtils.isAllBlank(userReq.getPwd(),userReq.getUname())){
            return Result.error("用户名密码不能为空");
        }
        Result<User> userResult=authRemote.findByUser(userReq.getUname());
        User user = userResult.getData();
        if(user==null){
            return Result.error("用户名不存在");
        }

        if(!user.getPwd().equals(userReq.getPwd())){
            return Result.error("密码错误");
        }

        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSON.toJSONString(user),30, TimeUnit.MINUTES);

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTime("30MIN");
        return Result.success(jwtResponse);
    }

    @Override
    public User getInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSON.parseObject(s, User.class);
    }
}
